package models

import (
	"time"

	"github.com/astaxie/beego/validation"
)

type Permission struct {
	Id          int       `gorm:"primaryKey" json:"id" form:"id"`
	Name        string    `valid:"Required;" json:"label" form:"name"` // 不能为空
	GuardName   string    `json:"guardName" form:"guardName"`
	SortOrder   int       `json:"sortOrder" form:"sortOrder"`
	Url         string    `json:"url" form:"url"`
	Level       int       `json:"level" form:"level"`
	Icon        string    `json:"icon" form:"icon"`
	ParentId    int       `json:"parentId" form:"parentId"`
	DisplayMenu int       `json:"displayMenu" form:"displayMenu"`
	Status      int       `json:"status" form:"status"`
	CreatedAt   time.Time `json:"createdAt" form:"createdAt"`
	UpdatedAt   time.Time `json:"updatedAt" form:"updatedAt"`
	DeletedAt   time.Time `json:"deletedAt"`
}

type Node struct {
	Permission
	Children []*Node `json:"children"`
}

func (m *Permission) TableName() string {
	return TableName("permissions")
}

// 自定义验证规则
func (m *Permission) SelfValid() (msg interface{}) {
	valid := validation.Validation{}
	if b, _ := valid.Valid(m); !b {
		for _, err := range valid.Errors {
			return err.Message
		}
	}
	return nil
}

func (n *Node) GetAuthTree(list []*Node, parentId int) []*Node {
	menu := make(map[int]*Node)
	for _, v := range list {
		if _, ok := menu[v.Id]; ok {
			v.Children = menu[v.Id].Children
			menu[v.Id] = v
		} else {
			v.Children = make([]*Node, 0)
			menu[v.Id] = v
		}
		if _, ok := menu[v.ParentId]; ok {
			menu[v.ParentId].Children = append(menu[v.ParentId].Children, menu[v.Id])
		} else {
			menu[v.ParentId] = &Node{Children: []*Node{menu[v.Id]}}
		}
	}
	return menu[parentId].Children
}
